<template>
  <el-table
    border
    ref="tableRef"
    class="dw-full"
    row-key="id"
    :data="tableData"
    highlight-current-row
    @selection-change="selectionChange"
    @row-dblclick="rowDblclick"
    @row-click="rowClick"
    :default-expand-all="true"
  >
    <template #empty>
      <div v-if="loading" class="dw-full" v-loading="loading" element-loading-text="数据加载中..."></div>
      <el-empty description="无数据" v-else> </el-empty>
    </template>
    <el-table-column v-if="showIndex" type="index" width="50" align="right" />
    <el-table-column v-if="checkbox" type="selection" width="38" />
    <el-table-column v-for="(column, index) in columns" :prop="column.prop" :key="index" :label="column.label" :width="column.width" :align="column.align">
      <template #default="scope" v-if="column.slotName">
        <slot :name="column.slotName" :scope="scope"></slot>
      </template>
    </el-table-column>
    <el-table-column v-if="showOperation" label="操作" :width="operationWidth" align="left" fixed="right">
      <template #default="scope">
        <span v-for="(item, index) in operationItems" :key="index">
          <el-button v-if="!item.slotName" :key="index" :icon="item.icon" :type="item.type" @click="item.onClick!(scope.$index, scope.row)" link>{{ item.text }}</el-button>
          <slot :name="item.slotName" :scope="scope" v-else></slot>
        </span>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    v-if="pagination"
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    class="pagination"
    :page-sizes="[30, 50, 80, 100]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>
<script setup lang="ts" generic="T extends IMasterEntity">
import type { IMasterEntity, IPageResult, ITreeEntity } from '@/types/entity';
import type { IColumn, IGetPageHttpConfig, IOperationItem } from '@/types/menu-datagrid-form';
import { dwHttp } from '@/utils/http';
import { onMounted, ref, type PropType } from 'vue';
import { translateDataToTree } from '@/utils/func';
defineOptions({
  name: 'DwDataGrid',
});
const props = defineProps({
  //行号
  showIndex: {
    type: Boolean,
    default: true,
  },
  //是否开启多选
  checkbox: {
    type: Boolean,
    default: true,
  },
  //列配置信息
  columns: {
    type: Array as PropType<IColumn[]>,
    required: true,
    default: () => {
      return [];
    },
  },
  showOperation: {
    type: Boolean,
    default: true,
  },
  operationWidth: {
    type: Number,
    default: 150,
  },
  operationItems: {
    type: Array as PropType<IOperationItem<T>[]>,
  },
  initLoaded: {
    type: Boolean,
    default: true,
  },
  isTree: {
    type: Boolean,
    default: false,
  },
  getPageHttpConfig: {
    type: Object as PropType<IGetPageHttpConfig<T>>,
    required: true,
  },
  pagination: {
    type: Boolean,
    default: true,
  },
});
const loading = ref(false);
const emits = defineEmits(['onRowDblclick', 'rowClick']);
const showIndex = ref<boolean>(props.showIndex);
const checkbox = ref<boolean>(props.checkbox);
const columns = ref<IColumn[]>(props.columns);
const isTree = props.isTree;
const operationItems = ref<IOperationItem<T>[]>(props.operationItems || []);
const initLoaded = props.initLoaded;
const getPageHttpConfig = props.getPageHttpConfig;
const pagination = props.pagination;
const currentPage = ref<number>(1);
const pageSize = ref<number>(30);
const total = ref<number>(0);
const tableData = ref<T[]>([]);
const tableRef = ref();
const currentRow = ref<T | undefined>(undefined);
onMounted(() => {
  if (initLoaded) {
    loadData();
  }
});
const loadData = () => {
  let params = {};
  let query = {};
  loading.value = true;
  tableData.value = [];
  if (getPageHttpConfig.query) {
    query = getPageHttpConfig.query() || {};
  }
  if (pagination && !isTree) {
    params = { pageSize: pageSize.value, currentPage: currentPage.value, ...query };
  } else {
    params = { ...query };
  }
  dwHttp({
    url: getPageHttpConfig.url,
    method: 'get',
    params: params,
    isSuccessTip: false,
  })
    .then((res) => {
      const { data } = res;
      let result: undefined | IPageResult<T>;
      if (getPageHttpConfig.render && typeof getPageHttpConfig.render === 'function') {
        result = getPageHttpConfig.render(data);
      } else {
        result = data as unknown as IPageResult<T>;
      }

      if (isTree) {
        const treeData = data as unknown as ITreeEntity[];
        tableData.value = translateDataToTree(treeData) as unknown as T[];
      } else {
        if (result === undefined) {
          result = { totalRow: 0, records: [] };
        }
        total.value = result.totalRow as number;
        tableData.value = result.records as unknown as T[];
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
const rowDblclick = (rowdata: T) => {
  emits('onRowDblclick', rowdata);
};
const rowClick = (rowdata: T) => {
  currentRow.value = rowdata;

  emits('rowClick', rowdata);
};
const handleSizeChange = () => {
  loadData();
};
const handleCurrentChange = () => {
  loadData();
};
const getSelectionRows = (): Array<T> => {
  return tableRef.value.getSelectionRows();
};

const selectionChange = () => {};
const getSelectionRow = () => {
  return currentRow.value;
};
defineExpose({ loadData, getSelectionRows, getSelectionRow });
</script>
<style lang="scss" scoped>
.dw-full {
  width: 100%;
  height: 100%;
}
.pagination {
  margin: 5px 0;
}
</style>
